import { 
  getPlanSummary, 
  getCoachRecommendations, 
  applyCoachRecommendation 
} from '../../http/api';
import eventBus from '../../utils/eventBus';

const app = getApp();
Page({
  data: {
    proteinTotal: '0.0',
    carbsTotal: '0.0',
    fatTotal: '0.0',
    waterTotal: '0.0',
    caloriesTotal: '0.0',
    coaches: []
  },
  onShow() {
    this.onLoad();
  },

  onLoad() {
    this.updatePlanSummary();
    this.loadPlanSummary();
    this.loadCoachRecommendations();
      // 监听食物添加事件
    eventBus.on('foodAdded', () => {
      this.loadPlanSummary();
      this.updatePlanSummary(); // 当有食物添加时，更新热量总值
  });
  },
  onUnload() {
    // 页面卸载时移除事件监听
    eventBus.off('foodAdded');
  },

  updatePlanSummary() {
    const { meals } = app.globalData;
    const totals = meals.reduce(
      (acc, meal) => ({
        totalCalories: acc.totalCalories + parseFloat(meal.totalCalories),
        totalProtein: acc.totalProtein + parseFloat(meal.totalProtein),
        totalFat: acc.totalFat + parseFloat(meal.totalFat),
        totalCarbohydrate: acc.totalCarbohydrate + parseFloat(meal.totalCarbohydrate)
      }),
      { totalCalories: 0, totalProtein: 0, totalFat: 0, totalCarbohydrate: 0 }
    );

    this.setData({
      proteinTotal: totals.totalProtein.toFixed(1),
      carbsTotal: totals.totalCarbohydrate.toFixed(1),
      fatTotal: totals.totalFat.toFixed(1),
      caloriesTotal: totals.totalCalories.toFixed(1)
    });
  },
  // 加载用户计划汇总
  loadPlanSummary() {
    const userId = wx.getStorageSync('userInfo').userId;
    if (!userId) return;

    wx.showLoading({ title: '加载中...' });
    getPlanSummary(userId)
      .then(res => {
        if (res.data.success) {
          const data = res.data.summary;
          this.setData({
            proteinTotal: data.totalProtein.toFixed(1),
            carbsTotal: data.totalCarbohydrate.toFixed(1),
            fatTotal: data.totalFat.toFixed(1),
            caloriesTotal: data.totalCalories.toFixed(1)
          });
        }
      })
      .catch(err => {
        wx.showToast({ title: '加载计划失败', icon: 'none' });
      })
      .finally(() => {
        wx.hideLoading();
      });
      
  },

  // 加载教练推荐
  loadCoachRecommendations() {
    wx.showLoading({ title: '加载中...2' });
    getCoachRecommendations()
      .then(res => {
        if (res.data.success) {
          this.setData({ 
            coaches: res.data.data.map(coach => ({
              ...coach,
              id: coach.recommendationId,
              meals: coach.meals.map(meal => ({
                ...meal,
                foods: meal.foods.map(item => ({
                  foodId: item.foodId,
                  name: item.foodName,
                  image: `https://wechatobject-1355794559.cos.ap-guangzhou.myqcloud.com/food/${item.image}.png`,
                  grams: item.grams
                }))
              }))
            }))
          });          
        }
      })
      .catch(err => {
        wx.showToast({ title: '加载推荐失败', icon: 'none' });
      })
      .finally(() => {
        wx.hideLoading();
      });
  },

  // 选择教练推荐
  onChooseCoach(e) {
    const recommendationId = e.currentTarget.dataset.id;
    const userId = wx.getStorageSync('userInfo').userId;
    
    wx.showModal({
      title: '确认',
      content: '确定要应用此推荐计划吗？当前计划将被替换',
      success: (res) => {
        if (res.confirm) {
          this.applyRecommendation(userId, recommendationId);
        }
      }
    });
  },

  applyRecommendation(userId, recommendationId) {
    wx.showLoading({ title: '应用中...' });
    applyCoachRecommendation(userId, recommendationId)
      .then(res => {
        if (res.data.success) {
          wx.showToast({ title: '应用成功' });
          this.loadPlanSummary();
        }
      })
      .catch(err => {
        wx.showToast({ title: '应用失败', icon: 'none' });
      })
      .finally(() => {
        wx.hideLoading();
      });
  },

  // 跳转到修改计划页面
  navigateToMealPage() {
    wx.navigateTo({
      url: '/pages/meal/meal?action=edit'
    });
  }
});